'use strict';
const {
	verifyToken
} = require('wx-common');
const db = uniCloud.database();
const msgCollection = db.collection('xxf-message');
const dbCmd = db.command;
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event);
	const {
		action,
		token,
		uid,
	} = event;
	if (!verifyToken(token)) {
		return {
			code: 401,
			message: 'Token无效'
		};
	}
	if (!uid) {
		return {
			msg: '用户ID参数错误！',
			code: 0,
			data: null
		};
	}
	switch (action) {
		case 'getNotice':
			return getNotice(event);
		case 'readNotice':
			return readNotice(event);
		case 'getMessage':
			return getMessage(event);
		default:
			return {
				msg: 'Invalid action！',
					code: 0,
					data: null
			};
	}
};
async function readNotice(params) {
	const {
		uid,
		id
	} = params;
	const before = await msgCollection.doc(id).get();
	console.log("before: ", before);
	const obj = before.data[0];
	let readList = [];
	if (obj && obj.read_list && obj.read_list.length && obj.read_list.indexOf(uid) >= 0) {
		console.log('已读!');
	} else {
		readList = obj.read_list || [];
		readList.push(uid);
	}

	console.log("readList: ", readList);
	const updateRes = await msgCollection.where({
		_id: id
	}).update({
		read_list: readList
	});
	console.log("updateRes: ", updateRes);
	if (updateRes.updated === 1) {
		return {
			msg: 'success',
			code: 1,
			data: true
		};
	} else {
		return {
			msg: 'fail',
			code: 0,
			data: false
		};
	}
}
async function getNotice(params) {
	const {
		uid,
	} = params;
	const oneRes = await msgCollection.where({
		type: "notice",
	}).get({
		getOne: true
	});
	console.log('oneRes: ', oneRes);
	if (oneRes.data && oneRes.data.length > 0) {
		return {
			msg: '',
			code: 1,
			data: {
				list: oneRes.data,
			}
		};
	} else {
		return {
			msg: '暂无数据！',
			code: 1,
			data: {
				list: []
			}
		};
	}
}
async function getMessage(params) {
	const {
		uid,
	} = params;
	const listRes = await msgCollection.get();
	console.log('listRes: ', listRes);
	if (listRes.data && listRes.data.length > 0) {
		return {
			msg: '',
			code: 1,
			data: {
				list: listRes.data,
			}
		};
	} else {
		return {
			msg: '暂无数据！',
			code: 0,
			data: {
				list: []
			}
		};
	}
}